/**
 * 配置LayaMe服务器
 * 老的: master-layame.layabox.com
 * 新的: master-maker.layaverse.com
 */
const URLADDRESS = {
    layame: "https://master-maker.layaverse.com"
}

/**
 * 异步请求
 * @param {*} infoObj : {url: String, openMethod?: "GET"|"POST", sendContent?: FormData|ArrayBuffer|...}
 * @param {*} sucFunc Function?
 * @param {*} errFunc Function?
 * @param {*} progressFunc Function?
 */
function getInfoFromServer(infoObj, sucFunc, errFunc, progressFunc) {
    return new Promise((resolve, reject) => {
        let
            url = infoObj.url,
            openMethod = infoObj.openMethod || "GET";
        let sendContent = openMethod === "GET" ? null : (infoObj.sendContent || null);
        let xhr = new XMLHttpRequest();
        xhr.open(openMethod, url, true);
        xhr.onreadystatechange = function (e) {
            if (xhr.readyState == 4 && xhr.status == 200) {
                let response = xhr.responseText;
                sucFunc instanceof Function && sucFunc(response);
                resolve(response);
            } else if (xhr.readyState == 4 && xhr.status !== 200) {
                reject(xhr.status);
            }
        };
        xhr.onerror = function (e) {
            errFunc instanceof Function && errFunc(response);
            reject(e);
        }
        xhr.send(sendContent);
        if (progressFunc instanceof Function) {
            xhr.upload.addEventListener("progress", function (e) {
                if (e.lengthComputable) {
                    let percentage = Math.round((e.loaded * 100) / e.total);
                    progressFunc(percentage);
                }
            }, false);
    
            xhr.upload.addEventListener("load", function (e) {
                progressFunc(100);
            }, false);
        }
    })
}

/**
 * 上传文件，请注意url及sendContent(本方法应仅用于可以获取文件路径，但无法获取File对象的情况)
 * @param {*} infoObj {url: String, sendContent?: Object}
 * @param {*} filePath String
 * @param {*} sucFunc Function?
 * @param {*} errFunc Function?
 * @param {*} progressFunc Function?
 */
function uploadFileToServer(infoObj, filePath, sucFunc, errFunc, progressFunc) {
    const fs = require("fs");
    let filebuffer = fs.readFileSync(filePath);
    let newInfoObj = {
        url: infoObj.url,
        openMethod: "POST",
        sendContent: filebuffer
    };
    return getInfoFromServer(newInfoObj, sucFunc, errFunc, progressFunc);
}

module.exports = { URLADDRESS, getInfoFromServer, uploadFileToServer };